<template>
	<view class="header-class" :style="[{top:CustomBar + 'px', minHeight: SeachBar + 'px', maxHeight: SeachBar + 'px'}]">
		<view class="address-view-class" v-if="isShowAddress">
			<text class="address-text" v-if='isShow' v-model="location_name_obj.name"
				@tap="addressBtn()">{{location_name_obj.name}}</text>
			<view class="address-img-addressSearch-view-class">
				<image class="address-image-addressSearch" src="@/static/downArrorw-black.png"
					@click="positioningBtn()">
				</image>
			</view>
		</view>
		<view class="inputView-addressSearch-view-class">
			<view class="inputboxClass-addressSearch-view-class">
				<image class="searchjingClass" src="@/static/search.png"></image>
				<input class="inputClass-addressSearch-view-class" @input="inputPhone" :placeholder="placeholderName"
					placeholder-class="uni-address-search-pcs" :value='inputValue' />
				<text class="inputTextClass-addressSearch-view-class" @tap="searchBtn()" v-if="showSearchBtn">搜索</text>
			</view>
		</view>
		<uni-popup ref="select_ctiy_popup" :animation="true" type="bottom" @maskClick="maskClickpopup()"
			:safeArea="true" @change="changePopup()">
			<view class="popup-content-view-box">
				<view class="select-ctiy-popup-title">城市地区</view>
<!-- 				<view class="inputboxClass-popup">
					<image class="searchjing-image" src="@/static/search.png"></image>
					<input class="inputClass-addressSearch-view-class" @input="inputPhone_address"
						placeholder="请输入省份/城市" placeholder-class="uni-address-search-pcs" />
				</view> -->
				<!-- <view class="list" :style="{gridTemplateColumns: `repeat(${lineNumCtiy},1fr)`}">
					<view v-for="(item,index) in popularCitiesData" :key="index">
						<view class="ctiy_item_box" @click="popularCitiesClick(item)">
							<view class="ctiy-item-text">{{item.name}}</view>
						</view>
					</view>
				</view> -->
				<view class="line-popup"></view>

				<view class="pcaPicker" @touchmove.stop.prevent="preventTouchMove">
					<view class="popBottom popRound">
						<picker-view :value="pcaIndex" @change="pcaChange">
							<picker-view-column>
								<block v-for="(item,index) in provinceData" :key="index">
									<view
										:class="pcaIndex[0]==index?'picker-view-item-text-select':'picker-view-item-text'">
										{{item.name}}
									</view>
								</block>
							</picker-view-column>
							<picker-view-column>
								<block v-for="(item,index) in provinceData[pcaIndex[0]].children" :key="index">
									<view
										:class="pcaIndex[1]==index?'picker-view-item-text-select':'picker-view-item-text'">
										{{item.name}}
									</view>
								</block>
							</picker-view-column>
						</picker-view>
					</view>
				</view>

				<view class="popup-btn-view popup-btn-text" @click="confirm()">确定</view>
				<view class="height20"></view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		getProvinceList,
		latLongGetAddress
	} from '@/api/base.js';
	import {
		popularCities,
		logisticsCity
	} from "@/api/logistics.js"
	export default {
		name: "addressSearch",
		props: {
			isShowAddress: {
				type: Boolean,
				default: true
			},
			addALLAddress: {
				type: Boolean,
				default: false
			},
			placeholderName:{
				type:String,
				default:() => '品牌 车系 车型 指导价'
			},
			inputValue:{
				type:String,
				default:() => ''
			},
			showSearchBtn: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				SeachBar: this.SeachBar,
				panche:'品牌 车系 车型 指导价',
				content: '',
				isShow: true,
				location_name_obj: {
					"name": "全国",
					'id': ''
				},


				lineNumCtiy: 5,
				pcaIndex: [0, 0],
				provinceData: [{
					children: {} //避免没有数据的时候一直报错找不到这个children
				}],
				popularCitiesData: [{
					children: {} //避免没有数据的时候一直报错找不到这个children
				}],
				// inputValue: '',

				addressObj: {
					"id": "",
					"parent_id": "0",
					"level": 1,
					"name": "全国",
					"children": [{
						"id": "",
						"parent_id": "",
						"level": 2,
						"name": "全国"
					}]
				}
			};
		},
		
		watch: {
			location_name_obj: {
				handler(newName, oldName) {
					this.isShow = false
					console.log("watch 检测数据发生变化时的 数据处理   " + JSON.stringify(newName))
					this.$nextTick(()=>{
						this.isShow = true
					})
					
				},
				immediate: true,
				deep: true
			}
		},
		beforeMount() {
			if (this.isShowAddress) {
				var that = this
				// uni.getStorage({
				// 	key: 'address',
				// 	success(res) {
				// 		that.$utils.log("打印获取缓存成功  " + JSON.stringify(res))
				// 		that.location_name_obj.name = res.data.name
				// 	},
				// 	fail(error) {
				// 		that.$utils.log("打印获取缓存失败  " + JSON.stringify(error))
				// 		// that.location_name_obj.name = '北京'
				// 		that.getLocationByUniAPI()
				// 	}
				// })
				const locationValue = uni.getStorageSync('address')
				console.log("打印获取到的地理位置缓存数据 +++++++ " + JSON.stringify(locationValue))
				if (locationValue) {
					that.location_name_obj = locationValue
				} else {
					console.log(" 获取当前定位 ------- ")
					// that.location_name_obj.name = '北京'
					that.getLocationByUniAPI()
				}

				const value = uni.getStorageSync('login')
				//请求省市数据
				getProvinceList().then(res => {
					var that = this
					that.$utils.log("打印请求省市数据   " + JSON.stringify(res))
					if (res.code == 0) {
						// that.isShow = false
						this.$nextTick(() => {
							that.provinceData = res.data
							if (that.addALLAddress) {
								that.provinceData.unshift(that.addressObj)
							}
							// that.isShow = true
						})
					}else{
						that.provinceData.unshift(that.addressObj)
					}
				})
				//请求热门常用城市
				// popularCities(value.id).then(res => {
				// 	this.$nextTick(() => {
				// 		that.popularCitiesData = res.data
				// 	})
				// })
			}
		},
		methods: {
			inputValueUpdata() {
				this.inputValue = ''
				this.$utils.log('进入')
			},
			//获取当前所在城市位置
			positioningBtn() {
				this.$utils.log("点击了地址按钮获取当前 经纬度 所对应的城市")
				this.getLocationByUniAPI()
			},
			//弹出位置授权框
			// 获取用户当前位置经纬度
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							resolve(res)
							this.$utils.log(res)
							this.$utils.log('当前位置的经度：' + res.longitude);
							this.$utils.log('当前位置的纬度：' + res.latitude);
						},
						fail: (err) => {
							reject(err)
							this.$utils.log(err)
						}
					})
				})
			},

			//判断用户是否授权位置
			authorizedLocation() {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: (res) => {
							this.$utils.log("打印uni.getSetting 返回的数据  " + JSON.stringify(res))
							// res.authSetting['scope.userLocation'] === undefined  表示 初始化进入，从未授权
							// res.authSetting['scope.userLocation'] === true       表示 已授权
							// res.authSetting['scope.userLocation'] === false      表示 授权拒绝
							if (res.authSetting['scope.userLocation'] === undefined) {
								// console.log("弹出位置授权框")
								this.getLocation().then((res) => {
									// 授权位置成功
									resolve(res)
								}).catch((err) => {
									// 授权位置失败
									reject(err)
									uni.showToast({
										title: '授权位置失败',
										icon: 'none',
										duration: 3000
									})
								})
							} else if (res.authSetting['scope.userLocation'] === true) {
								this.$utils.log("已经授权")
								resolve(res)
							} else if (res.authSetting['scope.userLocation'] === false) {
								this.$utils.log("弹出允许授权设置框")
								uni.showModal({
									title: '提示',
									content: '是否允许授权位置信息',
									confirmText: '去设置',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: (res) => {
													if (res.authSetting[
															'scope.userLocation'
														]) {
														resolve(res)
													} else {
														reject(res)
														uni.showToast({
															title: '授权失败',
															icon: 'none',
															duration: 3000
														})
													}
												},
												fail: (err) => {
													reject(err)
													uni.showToast({
														title: '打开设置异常',
														icon: 'none',
														duration: 3000
													})
												}
											})
										} else {
											reject(res)
											this.$utils.log(res)
										}

									},
									fail: err => {
										reject(err)
										uni.showToast({
											title: '弹窗异常',
											icon: 'none',
											duration: 3000
										})
									}

								})

							}
						}
					})
				})
			},
			// 根据经纬度得到位置信息
			getLocationInfo(location) {
				var that = this
				// this.$utils.log("打印获取到的经纬度  " + JSON.stringify(location))
				latLongGetAddress(location).then(res => {
					that.$utils.log("打印获取到的 地理位置信息  22222  " + JSON.stringify(res))
					if (res.code == 0) {
						const locationObj = {
							"name": res.data.city.slice(0, res.data.city.length - 1),
							"id": res.data.city_id + ''
						}
						that.location_name_obj = locationObj
						uni.setStorageSync('address', locationObj)
						that.isShow = false
						that.$nextTick(() => {
							that.isShow = true
						})
						that.$emit('addressBtn', locationObj)
						that.$forceUpdate()
					} else {
						uni.showToast({
							title: '获取当前位置失败，请选择城市',
							icon: 'none',
							duration: 1500
						})
					}
				})
			},

			// 通过 uni-app API 获取经纬度定位（该方法兼容性高）
			getLocationByUniAPI() {
				// #ifdef  MP-WEIXIN
				var that = this
				// 判断是否授权
				this.authorizedLocation().then((res) => {
					// 第一次授权
					if (res.errMsg === "getLocation:ok") {
						// that.$utils.log("res里面有什么！！！" + JSON.stringify(res))
						const long = res.latitude;
						const lat = res.longitude;
						let location = {
							long,
							lat
						}
						// 根据经纬度得到位置信息
						that.getLocationInfo(location)
					} else if (res.errMsg === "getSetting:ok") {
						//已授权
						that.$utils.log("getLocationByUniAPI   ----- 已授权" + JSON.stringify(res))
						that.getLocation().then((res) => {
							// 获取位置成功
							const long = res.latitude;
							const lat = res.longitude;
							let location = {
								long,
								lat
							}
							// 根据经纬度得到位置信息
							that.getLocationInfo(location)
						}).catch((err) => {
							// 授权位置失败
							reject(err)
							uni.showToast({
								title: '授权位置失败',
								icon: 'none',
								duration: 3000
							})
						})
					}
				}).catch((err) => {
					if (err.errMsg === "showModal:ok" && err.confirm == false) {
						that.$utils.log("getLocationByUniAPI   ----- catch" + err)
					}
				})
				// #endif

			},
			// 防穿透
			preventTouchMove() {},
			// 滚动切换
			pcaChange(e) {
				this.$utils.log(JSON.stringify(e))
				const currentIndex = e.detail.value;

				if (currentIndex[0] != this.pcaIndex[0]) {
					this.pcaIndex.splice(0, 2, currentIndex[0], 0);
				}
				if (currentIndex[1] != this.pcaIndex[1]) {
					this.pcaIndex.splice(1, 2, currentIndex[1]);
				}
				this.$utils.log("选择的所在城市" + JSON.stringify(this.pcaIndex))
			},
			confirm() {

				this.location_name_obj = this.provinceData[this.pcaIndex[0]].children[this.pcaIndex[1]]
				this.$refs.select_ctiy_popup.close()
				this.$utils.log("选择的所在城市" + JSON.stringify(this.location_name_obj))
				uni.setStorageSync('address', this.location_name_obj)
				this.$emit('addressBtn', this.location_name_obj)
			},
			popularCitiesClick(item) {
				this.$utils.log("选择的所在城市" + JSON.stringify(item))
				this.location_name_obj = item
				uni.setStorageSync('address', item)
				this.$emit('addressBtn', this.location_name_obj)
				this.$refs.select_ctiy_popup.close()
			},

			maskClickpopup() {},
			changePopup() {},
			//点击地图城市 进行弹窗
			addressBtn() {
				// this.getLocationByUniAPI()
				this.$refs.select_ctiy_popup.open()
				// this.$emit('addressBtn', this.location_name)
				this.$utils.log("点击了address 获取位置信息")
			},
			inputPhone(event) {
				this.content = event.target.value
				this.inputValue = event.target.value
				this.$utils.log("打印input输出的值" + this.content)
				if (this.content == '') {
					this.$emit('inputPhone')
				}
			},
			searchBtn() {
				console.log('输入',this.content);
				this.$emit('searchBtn', this.content)
			},
			//父组件调用该方法进行位置信息更新
			setAddres() {
				var that = this
				uni.showLoading()
				this.location_name_obj = uni.getStorageSync('address')
				setTimeout(() => {
					uni.hideLoading()
				}, 500)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header-class {
		width: 100%;
		display: flex;
		background-color: #4E6ECC;
		justify-content: center;
		align-items: center;
		position: fixed;
		z-index: 99;
	}

	.address-view-class {
		display: flex;
		flex-direction: row;
		margin-left: 18rpx;
	}

	.address-text {
		font-size: 32rpx;
		font-family: PingFangSC-Medium;
		color: #FFFFFF;
		opacity: 1;
		margin: 8rpx;
		max-width: 100rpx;

		overflow: hidden;
		-webkit-line-clamp: 1;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
	}

	.address-img-addressSearch-view-class {
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.address-image-addressSearch {
		width: 20rpx;
		height: 12rpx;
		background-color: #A1B1E0;
		padding: 14rpx 8rpx 10rpx 8rpx;
		border-radius: 8rpx;
	}

	.inputView-addressSearch-view-class {
		flex: 4;
		margin: 0rpx 10rpx;
	}

	.inputboxClass-addressSearch-view-class {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #fefefe;
		border-radius: 50rpx;
		margin: 10rpx;
	}

	.inputClass-addressSearch-view-class {
		flex: 1;
		padding: 0rpx;
		height: 72rpx;

		font-size: 28rpx;
		font-family: PingFangSC-Regular;
		font-weight: 500;
		opacity: 1;
		margin-left: 12rpx;
	}

	.inputTextClass-addressSearch-view-class {
		width: 112rpx;
		height: 64rpx;
		background: #0E59EA;
		opacity: 1;
		border-radius: 36rpx;
		margin: 4rpx 6rpx;
		display: flex;
		text-align: center;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		font-family: PingFangSC-Medium;
		line-height: 0rpx;
		color: #FFFFFF;
		opacity: 1;
	}

	.searchjingClass {
		margin-left: 26rpx;
		width: 30rpx;
		height: 30rpx;
	}

	.uni-address-search-pcs {
		font-size: 28rpx;
		font-family: PingFangSC-Regular;
		font-weight: 500;
		color: #999999;
		opacity: 1;
		margin-left: 12rpx;
		background-color: #FFFFFF00;
	}

	.bac-y {
		background-color: red;
		height: 500rpx;
		width: 100%;
	}

	/**
	 * 此处为popup css相关  -----start
	 **/
	.popup-content-view-box {
		width: 750rpx;
		height: auto;
		background: #FFFFFF;
		border-radius: 28rpx 28rpx 0rpx 0rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		/* 设置绝对定位 */
		position: absolute;
		/* 距离父元素上边缘  */
		bottom: -20rpx;
		z-index: 1;
		text-align: center;
	}

	.select-ctiy-popup-title {
		font-size: 32rpx;
		font-family: Alimama ShuHeiTi;
		font-weight: bold;
		color: #1C2125;
		margin-top: 60rpx;
	}

	.inputboxClass-popup {
		width: 694rpx;
		height: 72rpx;
		background: #F3F6FE;
		border: 1px solid #FFFFFF;
		border-radius: 36rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 18rpx;
		margin-top: 18rpx;
		text-align: left;
	}

	.searchjing-image {
		width: 30rpx;
		height: 30rpx;
		margin-left: 32rpx;
	}

	.ctiy_item_box {
		width: 128rpx;
		height: 58rpx;
		border: 2px solid #00000009;
		border-radius: 14rpx;
		line-height: 58rpx;
		text-align: center;
		margin: 4rpx;
	}

	.ctiy-item-text {
		font-size: 24rpx;
		font-family: Alimama ShuHeiTi;
		font-weight: 400;
		color: #333333;
		opacity: 1;
	}

	.height20 {
		height: 120rpx;
	}

	.line-popup {
		width: 100%;
		height: 14rpx;
		background: #F3F6FE;
		border-radius: 0rpx;
		// margin-top: 36rpx;
	}

	.popup-btn-view {
		width: 654rpx;
		height: 94rpx;
		background: #0E59EA;
		opacity: 1;
		border-radius: 14rpx;
		text-align: center;
		line-height: 94rpx;
		margin-top: 48rpx;
		margin-bottom: 30rpx;
	}

	.popup-btn-text {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: 500;
		color: #FFFFFF;
		opacity: 1;
	}

	picker-view {
		height: 300rpx;
	}

	.picker-view-item-text-select {
		text-align: center;
		line-height: 68rpx;
		font-size: 28rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #0E59EA;
		opacity: 1;
	}

	.picker-view-item-text {
		text-align: center;
		line-height: 68rpx;
		font-size: 28rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		opacity: 1;
	}

	.pcaPicker {
		height: 300rpx;
		width: 100%;
		background-color: #999999;
	}

	.pcaPicker>.popBottom {
		width: 100%;
		background-color: #ffffff;
		transition: all 0.3s ease;
		transform: translateY(100%);
	}

	.pcaPicker>.popRound {
		transition: all 0.3s ease;
		transform: translateX(0);
		opacity: 1;
	}

	/**
	 * 此处为popup css 相关  -----end
	 **/

	.list {
		display: grid;
	}
</style>